package net.dao.impl;

import net.dao.UserDao;
import net.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zyh on 2017/2/27.
 */

@Repository
public class UserDaoImpl implements UserDao{
    @Resource
    private SessionFactory sessionFactory;
    protected Session getSession(){
        Session session = sessionFactory.getCurrentSession();
        return session;
    }
    @Override
    public User findByUsernamePassword(String username, String password) {


        User user =null;
               user = (User) getSession().createQuery(
                "from User a where a.username = ? ")
                .setParameter(0,username)
                .uniqueResult();
        System.out.println(user);
        if (user==null){
            User user1 =new User(username,password);
            getSession().save(user1);
//
            return user1;
        }



        /*session.close();*/
        return null;
    }

    @Override
    public User loginByUsernamePassword(String username, String password) {
       Session session = sessionFactory.getCurrentSession();
        User user = null;
        user = (User) session.createQuery(
                "from User a where a.username = ? and a.password=?")
                .setParameter(0,username)
                .setParameter(1,password)
                .uniqueResult();
        System.out.println(user);
        if (user!=null){
            return user;
        }

        return null;
    }

    @Override
    public List<User> finAll() {
        return getSession().createQuery("from User ").list();
    }
}
